<?php

namespace app\controller\property\bill;

use think\App;
use app\controller\property\Base;
use app\validate\bill\BillFinanceValidate;
use app\common\repositories\bill\BillCateRepository;
use app\common\repositories\room\RoomBasicRepository;
use app\common\repositories\bill\BillFinanceRepository;
use app\common\repositories\property\basic\PropertyBasicRepository;

class BillFinance extends Base
{
    protected $repository;

    public function __construct(App $app, BillFinanceRepository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
        if (!$this->request->isAjax()) {
            $this->assign([
                'addAuth' => property_auth('propertyBillFinanceAdd'),
                'editAuth' => property_auth('propertyBillFinanceEdit'),
                'delAuth' => property_auth('propertyBillFinanceDel'),
            ]);
        }
    }

    protected function commonParams()
    {
        /** @var BillCateRepository $billCateRepository */
        $billCateRepository = app()->make(BillCateRepository::class);
        $cateNameData = $billCateRepository->getCascaderData($this->request->propertyId);
        $payMethodData = $this->repository::PAY_METHOD;
        $payTypeData = $this->repository::PAY_TYPE;
        $this->assign([
            'payTypeData' => $payTypeData,
            'cateNameData' => $cateNameData,
            'payMethodData' => $payMethodData,
        ]);
    }

    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'cates_id' => '',
                'cost_cate_id' => '',
                'user_id' => '',
                'pay_type' => '',
                'pay_method' => '',
                'keywords' => ''
            ]);
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
        $this->commonParams();
        return $this->fetch('bill/finance/list', [
            'detailAuth' => property_auth('propertyBillCourseDetail'),
        ]);
    }

    public function add()
    {
        if ($this->request->isAjax() && $this->request->isGet() && $this->request->param('get_type') == 'room') {
            /** @var RoomBasicRepository $poomBasicRepository */
            $poomBasicRepository = app()->make(RoomBasicRepository::class);
            $roomData = $poomBasicRepository->search([], $this->request->propertyId)
                ->append(['full_room_name'])
                ->select()->toArray();
            return json()->data(['code' => 0, 'data' => $roomData]);
        } elseif ($this->request->isPost()) {
            $param = $this->request->param([
                'contract_id' => '',
                'landlord_id' => '',
                'room_id' => '',
                'pay_method' => '',
                'energy_id' => '',
                'bill_id' => '',
                'bill_type' => '',
                'finance_no' => '',
                'cate_id' => '',
                'finance_type' => '',
                'start_date' => '',
                'end_date' => '',
                'amount' => '',
                'remark' => '',
            ]);
            $param['pay_type'] = 2;
            validate(BillFinanceValidate::class)->scene('add')->check($param);
            if ($this->repository->fieldExists('finance_no', $param['finance_no'])) {
                return $this->error($param['finance_no'] . '流水编号已存在');
            }
            try {
                $res = $this->repository->addInfo($this->request->propertyId, $param, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加财务流水失败', $e);
                return $this->error('网络错误');
            }
        } else {
            $this->commonParams();
            return $this->fetch('bill/finance/add', [
                'repairNo' => 'F' . date('ymd') . get_rand_member(8)
            ]);
        }
    }

    /**
     * 编辑
     * @return array|string|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->get($id);
        if (!$info) {
            return $this->error('信息获取失败');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'start_date' => '',
                'end_date' => '',
                'pay_method' => '',
                'amount' => '',
                'remark' => '',
            ]);
            validate(BillFinanceValidate::class)->scene('edit')->check($param);
            try {
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->success('数据无变化');
                }
            } catch (\Exception $e) {
                exception_log('编辑财务流水失败', $e);
                return $this->success('修改失败');
            }
        } else {
            $this->commonParams();
            return $this->fetch('bill/finance/edit', [
                'info' => $info,
            ]);
        }
    }

    public function detail()
    {
        $financeId = (int)$this->request->param('id');
        if ($financeId <= 0) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($financeId);
        if ($info['id'] <= 0) {
            return $this->error('财务流水不存在');
        }
        $this->commonParams();
        return $this->fetch('bill/finance/detail', [
            'info' => $info,
        ]);
    }


    public function del()
    {
        $ids = (array)$this->request->param('ids');
        try {
            $data = $this->repository->batchDelete($ids, $this->request->userId);
            if ($data) {
                return $this->success('删除财务流水成功');
            } else {
                return $this->error('删除财务流水失败');
            }
        } catch (\Exception $e) {
            exception_log('删除财务流水失败', $e);
            return $this->error('网络失败');
        }
    }


}